package com.changgou.web.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    private static final String LOGIN_URL="http://localhost:8001/api/oauth/toLogin";

    @Autowired
    private StringRedisTemplate redisTemplate;

    //exchange: web信息的交换机
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //判断是否是登录请求 如果是登录请求 放行
        if (request.getURI().getPath().contains("/api/oauth/login")||!UrlFilter.hasAuthorize(request.getURI().getPath())){
            return chain.filter(exchange);
        }

        //如果不是登录请求 切请求中没有携带jti 拒绝访问
        String jti=this.getJtiFromCookie(request);
        if (StringUtils.isEmpty(jti)){
            /*response.setStatusCode(HttpStatus.UNAUTHORIZED);//设置响应状态码401
            return response.setComplete();*/
            //跳转登录页面
            return this.toLoginPage(LOGIN_URL+"?from="+request.getURI(),exchange);
        }

        //如果请求中携带jti 但是redis没有token 拒绝访问
        //从redis中获取token
        String token=this.getTokenFromRedis(jti);
        //判断token是否存在
        if (StringUtils.isEmpty(token)){
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            return response.setComplete();
            return this.toLoginPage(LOGIN_URL+"?from="+request.getURI(),exchange);
        }

        //校验通过 对请求头进行增强
        request.mutate().header("authorization","Bearer "+token);

        //放行
        return chain.filter(exchange);
    }

    //跳转登录页面
    private Mono<Void> toLoginPage(String loginUrl, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location",loginUrl);
        return response.setComplete();
    }

    //从redis中获取token
    private String getTokenFromRedis(String jti) {
        return redisTemplate.boundValueOps(jti).get();
    }

    //从cookie中获取jti
    private String getJtiFromCookie(ServerHttpRequest request) {
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        HttpCookie cookie = cookies.getFirst("uid");
        if (cookie!=null){
            return cookie.getValue();
        }
        return null;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
